<template>
  <div class="app-container">
    <!-- 移动端骨架屏 -->
    <mobile-skeleton 
      v-if="isMobile && loading" 
      :showHeader="false"
      :showSearch="true" 
      :searchFields="1"
      :cardsCount="3"
      :showPagination="total > 0"
    />
    
    <!-- 移动端上下布局 -->
    <template v-else-if="isMobile">
      <!-- 移动端分类树 -->
      <div v-if="showTree" class="mobile-tree-container">
        <div class="mobile-tree-header">
          <span :style="{ color: theme }">{{ title }}</span>
          <el-button 
            type="text" 
            icon="el-icon-arrow-up" 
            @click="showTree = false" 
            :style="{ color: theme }"
            v-if="showTree">
            收起
          </el-button>
        </div>
        <CourseTree :title="title" @search="getList" />
      </div>
      <div v-else class="mobile-tree-toggle">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-button 
              type="primary" 
              size="small" 
              icon="el-icon-arrow-down"
              @click="showTree = true"
              :style="{
                backgroundColor: theme,
                borderColor: theme,
                width: '100%',
                marginBottom: '10px',
                borderRadius: '4px',
                height: '36px'
              }">
              展开考试分类
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 移动端搜索表单 -->
      <div class="course_content">
        <el-row type="flex" justify="around" style="width: 100%" class="mobile-search">
          <el-col :span="24">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" class="mobile-form">
              <el-form-item label="考试名称">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入考试名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <!-- 移动端工具栏 -->
        <el-row :gutter="10" class="mb8 mobile-toolbar">
          <right-toolbar :showSearch.sync="showSearch" :showTree.sync="showTree" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 移动端卡片视图 -->
        <div class="mobile-card-view">
          <div v-if="List.length === 0" class="empty-data">
            <i class="el-icon-document"></i>
            <p>暂无数据</p>
          </div>
          
          <el-card v-for="(item, index) in List" :key="index" class="mobile-card" shadow="hover">
            <div slot="header" class="card-header">
              <div class="card-title" :style="{ color: theme }">{{ item.name }}</div>
            </div>
            <div class="card-content">
              <div class="info-list">
                <div class="info-item">
                  <span class="label">考试总人数：</span>
                  <span class="value">{{ item.count }}</span>
                </div>
                <div class="info-item">
                  <span class="label">及格人数：</span>
                  <span class="value">{{ item.pass_count }}</span>
                </div>
                <div class="info-item">
                  <span class="label">及格率：</span>
                  <span class="value">{{ item.pass_rate }}%</span>
                </div>
              </div>
              
              <div class="exam-details" v-if="expandedCards[index]">
                <div class="details-section">
                  <div class="info-item">
                    <span class="label">考试时长：</span>
                    <span class="value">{{ item.time_limit }}分钟</span>
                  </div>
                  <div class="info-item">
                    <span class="label">试卷总分：</span>
                    <span class="value">{{ item.total_score }}分</span>
                  </div>
                  <div class="info-item">
                    <span class="label">及格分数：</span>
                    <span class="value">{{ item.qualify_score }}分</span>
                  </div>
                  <div class="info-item">
                    <span class="label">创建时间：</span>
                    <span class="value">{{ item.create_time | formatDate }}</span>
                  </div>
                </div>
              </div>
              
              <div class="card-toggle">
                <el-button type="text" size="small" @click.stop="expandCard(index)">
                  {{ expandedCards[index] ? '收起' : '查看详情' }}
                  <i :class="expandedCards[index] ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                </el-button>
              </div>
              
              <div class="card-actions">
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="handleStatistics(item)"
                  :style="{
                    backgroundColor: theme,
                    borderColor: theme
                  }"
                  v-hasPermi="['exam:statistics:query']">
                  查看统计
                </el-button>
              </div>
            </div>
          </el-card>
          
          <!-- 移动端分页 -->
          <div class="mobile-pagination" v-if="total > 0">
            <div class="mobile-pagination-wrapper">
              <!-- 第一行：总数和每页条数 -->
              <div class="pagination-row top-row">
                <span class="el-pagination__total">共 {{ total }} 条</span>
                <el-select 
                  v-model="queryParams.page_size" 
                  size="mini" 
                  class="el-pagination__sizes"
                  @change="handleSizeChange">
                  <el-option
                    v-for="item in [10, 20, 30, 50]"
                    :key="item"
                    :label="`${item}条/页`"
                    :value="item">
                  </el-option>
                </el-select>
              </div>
              
              <!-- 第二行：页码导航 -->
              <div class="pagination-row bottom-row">
                <el-pagination
                  background
                  @current-change="handleCurrentChange"
                  :current-page="queryParams.page"
                  :page-size="queryParams.page_size"
                  layout="prev, pager, next, jumper"
                  :total="total">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 桌面端左右布局 -->
    <el-row :gutter="24" v-else>
      <!-- 左侧树形 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="filterText"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <CourseTree :title="title" @search="getList" />
        </div>
      </el-col>
      <!-- 右侧内容 -->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <el-form-item label="考试名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入考试名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              :style="{
                backgroundColor: theme,
                borderColor: theme,
              }"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="List"
          row-key="id"
          border
          :default-sort="{ prop: 'create_time', order: 'descending' }"
        >
          <el-table-column
            label="考试名称"
            align="center"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="考试时长（分钟）"
            align="center"
            prop="time_limit"
          />
          <el-table-column
            label="试卷总分"
            align="center"
            prop="total_score"
          />
          <el-table-column
            label="及格分数"
            align="center"
            prop="qualify_score"
          />
          <el-table-column
            label="考试总人数"
            align="center"
            prop="count"
          />
          <el-table-column
            label="及格人数"
            align="center"
            prop="pass_count"
          />
          <el-table-column
            label="及格率"
            align="center"
            prop="pass_rate"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.pass_rate }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="create_time"
            sortable
          >
            <template slot-scope="scope">
              <span>{{ scope.row.create_time | formatDate }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-data"
                @click="handleStatistics(scope.row)"
                v-hasPermi="['exam:statistics:query']"
                >查看统计</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.page_size"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { examResultAll } from "@/api/vadmin/exam/exam";
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import CourseTree from "@/components/CourseTree";
import MobileSkeleton from "@/components/MobileSkeleton";
import "@/assets/styles/mobile/exam.scss";

export default {
  name: "resultsAll",
  components: { CourseTree, MobileSkeleton },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showTree: false,
      // 总条数
      total: 0,
      // 表格数据
      List: [],
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        name: undefined,
        course: undefined,
      },
      filterText: "",
      title: "考试分类",
      isMobile: false,
      mediaQueryList: null,
      expandedCards: {},
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  created() {
    this.getList();
  },
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },
  methods: {
    /** 查询列表 */
    getList(course) {
      this.loading = true;
      if (course) {
        this.queryParams.course = course.id;
      }
      examResultAll(this.queryParams).then((response) => {
        this.List = response.results;
        this.total = response.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        desc: undefined,
        status: 1,
        sort: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.course = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 考试统计按钮操作 */
    handleStatistics(row) {
      this.$router.push({
        path: "/vadmin/exam/statistics/" + row.id,
      });
    },
    /** 分页大小变化 */
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getList();
    },
    /** 当前页码变化 */
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
    /** 展开/收起卡片详情 */
    expandCard(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    }
  },
};
</script>

<style lang="scss" scoped>
.course_content {
  width: 100%;
  height: 100%;
}

/* 移动端工具栏样式 */
@media screen and (max-width: 767px) {
  .mobile-toolbar {
    margin-bottom: 10px !important;
    
    .el-row {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 8px;
      padding: 0 10px;
      
      .el-button {
        margin: 0;
        padding: 7px 12px;
        font-size: 12px;
        height: auto;
        line-height: 1.2;
      }
      
      .el-button-group {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .el-button {
          margin: 0;
        }
      }
    }
  }
  
  /* 移动端搜索表单样式优化 */
  .mobile-search {
    .el-form {
      padding: 10px;
      
      .el-form-item {
        margin-bottom: 10px;
        width: 100%;
        
        .el-form-item__content {
          width: 100%;
          
          .el-input {
            width: 100%;
          }
        }
      }
    }
  }
  
  /* 移动端卡片视图样式优化 */
  .mobile-card-view {
    padding: 0 10px;
    
    .mobile-card {
      margin-bottom: 15px;
      
      .card-header {
        padding: 10px;
        
        .card-title {
          font-size: 16px;
          font-weight: 500;
        }
      }
      
      .card-content {
        padding: 10px;
        
        .info-list {
          margin-bottom: 15px;
          
          .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            
            .label {
              color: #666;
            }
            
            .value {
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}
</style>